#自定义过滤器
from flask import current_app
from flask import g
from flask import session

from info.models import User


def index_filter(index):
    if index == 0:
        return "first"
    elif index == 1:
        return "second"
    elif index ==2:
        return "third"
    else:
        return " "

#装饰器不改变原有代码的情况下，添加新功能
def login_required(f):
    def wrapper(*args,**kwargs):
        # 从redis数据库中获取user_id
        user_id = session.get("user_id")
        user = None
        if user_id:
            try:
                user = User.query.get(user_id)
            except Exception as e:
                current_app.logger.error(e)
        #使用应用上下文对象g,用来请求过程中来存储临时数据
        g.user =user
        return f(*args,**kwargs)
    #在返回内部函数前，让被装饰器的函数名重新复制给内部函数
    wrapper.__name__= f.__name__
    return wrapper

